#include "bookmarkdialog.h"
#include "ui_bookmarkdialog.h"

BookmarkDialog::BookmarkDialog(QWidget *parent,CodeEditor* codeEditor)
    : QDialog(parent)
    , ui(new Ui::BookmarkDialog)
{
    ui->setupUi(this);
    pCodeEditor = codeEditor;

    updateBookmarkList();
}

BookmarkDialog::~BookmarkDialog()
{
    delete ui;
}

void BookmarkDialog::updateBookmarkList()
{
    QMap<int, QString> bookmarks = pCodeEditor->getBookmarks();
    ui->listWidget->clear();
    for (auto it = bookmarks.constBegin(); it != bookmarks.constEnd(); ++it) {
        QString itemText = QString("%1: %2").arg(it.key()).arg(it.value());
        ui->listWidget->addItem(itemText);
    }
}

void BookmarkDialog::on_btnCancel_clicked()
{
    // 保存书签
    pCodeEditor->saveBookmarks(pCodeEditor->filePath);

    accept();
}


void BookmarkDialog::on_btnAdd_clicked()
{
    // 获取当前位置
    int lineNumber = pCodeEditor->textCursor().blockNumber() + 1;
    // 获取标签名字
    QString name = ui->lineEdit->text();

    // 加入标签
    pCodeEditor->addBookmark(name, lineNumber);
    // 更新listWidget

    updateBookmarkList();
}


void BookmarkDialog::on_btnLocation_clicked()
{
    QListWidgetItem *selectedItem = ui->listWidget->currentItem();
    if (selectedItem) {
        QString itemText = selectedItem->text();
        int lineNumber = itemText.split(":")[0].toInt();
        pCodeEditor->jumpToBookmark(lineNumber);
    }
}


void BookmarkDialog::on_btnDelete_clicked()
{
    QListWidgetItem *selectedItem = ui->listWidget->currentItem();
    if (selectedItem) {
        QString itemText = selectedItem->text();
        int lineNumber = itemText.split(":")[0].toInt();
        pCodeEditor->removeBookmark(lineNumber);
        updateBookmarkList();
    }
}

